package hotel.switchs.oversea.biz.controller;

import com.alibaba.fastjson.JSONObject;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.dto.meituan.PushHotelBreakfastVo;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.vo.meituan.MtHotelRoomDownVo;
import hotel.base.oversea.vo.meituan.request.goods.ProductFailureVo;
import hotel.base.oversea.vo.meituan.response.goods.MtfpHotelGoodsCancelRuleFpApiVo;
import hotel.switchs.oversea.api.VO.request.*;
import hotel.switchs.oversea.api.dto.SwitchCreateRoomDto;
import hotel.switchs.oversea.api.dto.SwitchSaleRoomAboutIdsDto;
import hotel.switchs.oversea.api.entity.SwitchCreateRoomEntity;
import hotel.switchs.oversea.api.entity.SwitchCreateRoomFailureEntity;
import hotel.switchs.oversea.biz.config.service.RedisService;
import hotel.switchs.oversea.biz.mapper.SwitchCreateRoomFailureMapper;
import hotel.switchs.oversea.biz.mapper.SwitchCreateRoomMapper;
import hotel.switchs.oversea.biz.mapper.SwitchInterfaceCallNumberMapper;
import hotel.switchs.oversea.biz.mapper.SwitchRoomPriceSetMapper;
import hotel.switchs.oversea.biz.service.*;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;


/**
 * 创建售卖房型控制
 * @Author lmf
 * @Date 2020/6/10 13:39
 **/
@Slf4j
@RestController
@RequestMapping("/switchCreateRoom")
@Api(value = "SwitchCreateRoomController",tags = {"创建售卖房型"})
public class SwitchCreateRoomController {
    @Autowired
    SwitchCreateRoomService switchCreateRoomService;
    @Autowired
    SwitchPushRoomService switchPushRoomService;
    @Autowired
    SwitchRoomPriceSetMapper switchRoomPriceSetMapper;

    @Autowired
    SwitchCreateRoomFailureMapper switchCreateRoomFailureMapper;
    @Autowired
    SwitchCreateRoomMapper switchCreateRoomMapper;

    @Autowired
    RedisService redisService;

    @Autowired
    SwitchInterfaceCallNumberMapper switchInterfaceCallNumberMapper;


    @Autowired
    SwitchHotelUpService switchHotelUpService;

    @Autowired
    SwitchHotelActiveTagService switchHotelActiveTagService;

    @Autowired
    SwitchSubHotelInfoService switchSubHotelInfoService;

    @Autowired
    SwitchCancelRuleSetService switchCancelRuleSetService;
    @Autowired
    SwitchRoomPriceService switchRoomPriceService;




    /**
     * 分页获取，返回携程创建售卖房型对应的美团产品ids
     * @param jsonObject
     * @return
     */
    @PostMapping("/getMtIdsPageAboutSwitchSaleRoom")
    @ApiOperation(value = "分页返回可售卖房型id信息",notes="必须经过auth授权")
    public Result<Object> getMtIdsPageAboutSwitchSaleRoom(@RequestBody JSONObject jsonObject){
        //参数校验
        Integer index = (Integer)jsonObject.get("index");
        Integer pageSize = (Integer)jsonObject.get("pageSize");
        if(null == index ){
            return new Result<>("index不可为空");
        }
        if(null == pageSize){
            return new Result<>("pageSize不可为空");
        }
        //发起请求并保存数据
        return  switchCreateRoomService.getMtIdsPageAboutSwitchSaleRoom(index,pageSize);
    }

    /**
     * 创建售卖房型
     * 只需传子酒店id和子物理房型id
     * 会返回对应的美团产品的个数，然后累计起来超过10-15次休息一分钟 因为接口最多一分钟十次，偶尔超过十次
     */
    @PostMapping("/createRoom")
    @ApiOperation(value = "创建售卖房型",notes = "必须经过oauth授权")
    public Result<Object> aspcreateRoom(@RequestBody Map<String,Object> params){
        int  hotelId;
        int basicRoomTypeId;
        if(params.containsKey("hotelId")){
           hotelId= (int) params.get("hotelId");
        }else{
            return new Result<>("子酒店id为空");
        }
        if(params.containsKey("basicRoomTypeId")){
            basicRoomTypeId= (int) params.get("basicRoomTypeId");
        }else{
            return new Result<>("子物理房型id为空");
        }
       return switchCreateRoomService.createRoom(hotelId,basicRoomTypeId);
    }

    /**
     * 内部接口  根据美团产品id获取售卖房型信息
     * @return
     */
    @PostMapping("/getSaleRoomByMtGoodsId")
    @ApiOperation(value = "根据美团产品id获取售卖房型信息",notes = "必须经过oauth授权")
    public Result<Object> getSaleRoomByMtGoodsId(@RequestBody JSONObject jsonObject){
        if(ObjectUtils.isEmpty(jsonObject.get("mtGoodsId"))){
            return new Result<>("mtGoodsId不可为空");
        }
        if(ObjectUtils.isEmpty(jsonObject.get("mtHotelId"))){
            return new Result<>("mtHotelId不可为空");
        }
        SwitchCreateRoomDto roomDto ;
        try{
            roomDto = switchCreateRoomService.selectOneDtoByMtGoodsId(jsonObject.getInteger("mtGoodsId"),jsonObject.getString("mtHotelId"));
        }catch (Exception e){
            log.error("getSaleRoomByMtGoodsId  根据美团产品id获取售卖房型信息  异常  ");
            log.error(e.getMessage(),e);
            return new Result<>("error", CommonConstants.REQUEST_ERROR);
        }
        return new Result<>(roomDto);
    }

    /**
     * 内部接口  根据美团产品id获取售卖房型信息
     * @return
     */
    @PostMapping("/getMtIdsAboutSwitchSaleRoomByMtHotelId")
    @ApiOperation(value = "根据美团酒店id获取售卖房型信息",notes = "必须经过oauth授权")
    public Result<List<SwitchSaleRoomAboutIdsDto>> getMtIdsAboutSwitchSaleRoomByMtHotelId(@RequestBody JSONObject jsonObject){
        if(ObjectUtils.isEmpty(jsonObject.get("mtHotelId"))){
            return new Result<>("mtHotelId不可为空");
        }
        List<SwitchSaleRoomAboutIdsDto> list ;
        try{
            list = switchCreateRoomService.selectDtosByMtHotelId(jsonObject.getString("mtHotelId"));
        }catch (Exception e){
            log.error("getMtIdsAboutSwitchSaleRoomByMtHotelId  根据美团酒店id获取售卖房型信息  异常  ");
            log.error(e.getMessage(),e);
            return new Result<>("error", CommonConstants.REQUEST_ERROR);
        }
        return new Result<>(list);
    }

    /**
     * 内部接口  根据房间id获取房间信息
     * @return
     */
    @PostMapping("/getRoomByRoomId")
    @ApiOperation(value = "获取售卖房间根据房间id",notes = "必须经过oauth授权")
    public Result<Object> getRoomByRoomId(@RequestBody JSONObject jsonObject){
        if(ObjectUtils.isEmpty(jsonObject.get("mtRoomId"))){
            return new Result<>("mtRoomId不可为空");
        }
        SwitchCreateRoomDto roomDto ;
        try{
            roomDto = switchCreateRoomService.selectOneDtoByRoomId(jsonObject.getInteger("mtRoomId"));
        }catch (Exception e){
            log.error("getRoomByRoomId  获取售卖房间根据房间id  异常  ");
            log.error(e.getMessage(),e);
            return new Result<>("error", CommonConstants.REQUEST_ERROR);
        }
        return new Result<>(roomDto);
    }
    //MtfpHotelGoodsCancelRuleVo
    /**
     * 如果售卖房型的取消规则发生变化，就进行推送
     */
    @PostMapping("/pushRoomCancelRule")
    @ApiOperation(value = "售卖房型推送价格房量",notes = "必须经过oauth授权")
    public Result<Object> aspPushRoomCancelRule(@RequestBody MtfpHotelGoodsCancelRuleFpApiVo mtfpHotelGoodsCancelRuleFpApiVo){
        log.info("=============请求的数据为{}=======",mtfpHotelGoodsCancelRuleFpApiVo);
        return switchPushRoomService.pushRoomCancelRule(mtfpHotelGoodsCancelRuleFpApiVo.getCancelRuleList());
    }
    /**
     * 售卖房型推送价格 房量 房态 ,该房型就可以进行售卖了
     */
    @PostMapping("/pushRoomData")
    @ApiOperation(value = "售卖房型推送价格房量",notes = "必须经过oauth授权")
    public Result<Object> asppushRoomData(@RequestBody PushRoomDataVo pushRoomDataVo){
        int  hotelId;
        int basicRoomTypeId;
        if(pushRoomDataVo.getHotelId()<1) {
            return new Result<>("子酒店id为空");
        }
        if(pushRoomDataVo.getRoomId()<1) {
            return new Result<>("售卖房型id为空");
        }
        hotelId=pushRoomDataVo.getHotelId();
        basicRoomTypeId=pushRoomDataVo.getRoomId();
        int genre=pushRoomDataVo.getGenre();
        //该字段是为了手动调用接口修改价格
      //  return switchPushRoomService.pushRoomData(hotelId,basicRoomTypeId,genre);
        return switchPushRoomService.pushRoomDataByCancel(hotelId,basicRoomTypeId,genre);
    }

    /***
    * @Author: lmf
    * @Date: 2020/12/25
     * 查询售卖酒店房型是否有产品，有的话修改创建状态进行跑
    */
    @GetMapping("/checkSaleHotelRoomHavingGood")
    @ApiOperation(value = "查询售卖酒店房型是否有产品，有的话修改创建状态进行跑",notes = "必须经过oauth授权")
    public Result<Object>  checkSaleHotelRoomId(){
        return switchHotelUpService.checkSaleHotelRoomId();
    }


    /**
     * 售卖房型推送价格 房量 房态 ,该房型就可以进行售卖了
     */
    @PostMapping("/pushAllRoomData")
    @ApiOperation(value = "多个售卖房型推送价格房量",notes = "必须经过oauth授权")
    public Result<Object> asppushAllRoomData(@RequestBody Map<String,Object> params){
        int  hotelId;
        int[] basicRoomTypeId;
        if(params.containsKey("hotelId")){
            hotelId= (int) params.get("hotelId");
        }else{
            return new Result<>("子酒店id为空");
        }
        if(params.containsKey("roomId")){
            basicRoomTypeId= (int[]) params.get("roomId");
        }else{
            return new Result<>("售卖房型id为空");
        }
        return switchPushRoomService.pushAllRoomData(hotelId,basicRoomTypeId);
    }

    /**
     * 根据rogKey查询推价的结果
     * 如果推送价格失败，所以推送
     */
    @PostMapping("/pushRoomDataLog")
    @ApiOperation(value = "根据rogKey查询推价的结果",notes = "必须经过oauth授权")
    public Result<Object> getPushRoomDataLog(@RequestParam String logKey, @RequestParam(value = "type",defaultValue = "1")Integer type){
        log.info("rogkey的值为{}",logKey);
        return switchPushRoomService.getPushRoomDataLog(logKey,type);
    }
    /**
     * 调用美团下单前效验，如果返回999推送房量
     *  售卖房型id 子酒店id 库存
     */
    @PostMapping("/modifyRemain")
    @ApiOperation(value = "下单前效验如果库存充足,更新库存",notes = "必须经过oauth授权")
    public Result<Object> aspmodifyRemain(@RequestBody ModifyRemainVo modifyRemainVo) throws Exception {
        int hotelId=modifyRemainVo.getHotelId();
        if(hotelId<1){
            return new Result<>("子酒店id不能为空");
        }
        int roomId=modifyRemainVo.getRoomId();
        if(roomId<0){
            return new Result<>("售卖房型id不能为空");
        }
        String time=modifyRemainVo.getTime();
        if(StringUtils.isEmpty(time)){
            return new Result<>("入住日期不能为空");
        }
        String endTime=modifyRemainVo.getEndTime();
        if(StringUtils.isEmpty(endTime)){
            return new Result<>("离店日期不能为空");
        }
        int num=modifyRemainVo.getNum();
        if(num<0){
            return new Result<>("库存不能为0");
        }
        return switchPushRoomService.modifyRemain(modifyRemainVo);
    }
    /**
     * 美团产品价格变化，推送价格 单个
     * 产品id  时间:比如是2020-7-1到2020-7-2 传的是2020-7-1
     */
    @PostMapping("/modifyPrice")
    @ApiOperation(value = "美团产品价格变化，推送价格",notes = "必须经过oauth授权")
    public Result<Object> aspmodifyPrice(@RequestBody ModifyPriceVo modifyPriceVo) throws Exception {
        int goodId=modifyPriceVo.getMtGoodId();
        if(goodId<1){
            return new Result<>("产品id不能为空");
        }
        String time=modifyPriceVo.getTime();
        if(StringUtils.isEmpty(time)){
            return new Result<>("查询日期不能为空");
        }
        int price=modifyPriceVo.getPrice();
        if(price<1){
            return new Result<>("美团价格不能为空");
        }
        return switchPushRoomService.modifyPrice(modifyPriceVo);
    }
    /**
     * 获取能推送价格的房型id列表
     * 1.新创建的房型6分钟不能推送
     * 2.推送的前面俩天的房型 提前俩天进行推送
     */
    @GetMapping("/getCanPushRoomIdList")
    @ApiOperation(value = "获取可推送的售卖房型列表",tags = "必须经过oauth授权")
    public Result<Map<Integer,Object>> getCanPushRoomList(@RequestParam(value = "page",defaultValue = "1")int page){
        return switchPushRoomService.getCanPushRoomList(page);
    }

    /**
     * 更新房态状态
     * 产品id goodsId 日期:time 状态:status 0满房,可预订,不可预订 1可预订
     * @param modifyStatusVo
     * @return
     * @throws Exception
     */
    @PostMapping("/modifyStaus")
    @ApiOperation(value = "修改售卖房型房态状态",notes = "必须经过oauth授权")
    public Result<Object> aspmodifyStaus(@RequestBody ModifyStatusVo modifyStatusVo) throws Exception {
        int goodId=modifyStatusVo.getMtGoodId();
        if(goodId<1){
            return new Result<>("产品id不能为空");
        }
        String time=modifyStatusVo.getTime();
        if(StringUtils.isEmpty(time)){
            return new Result<>("查询日期不能为空");
        }
        return switchPushRoomService.modifyStaus(modifyStatusVo);
    }
    /**
     * @author: lmfroomFailure
     * @date: 2020/8/14 13:40
     * 美团酒店下线 拉入黑名单
     */
    @PostMapping("/downHotel")
    @ApiOperation(value = "美团酒店下线对应携程酒店也得下线",notes = "必须经过oauth授权")
    public Result<Object> aspdownHotel(@RequestBody SetHotelOnlineVo setHotelOnlineVo){
        int mtHotelId=setHotelOnlineVo.getMtHotelId();
        if(ObjectUtils.isEmpty(mtHotelId)||mtHotelId<1){
            return new Result<>("美团酒店id不能为空");
        }
        return switchHotelUpService.downHotel(setHotelOnlineVo);
    }
    /**
     * @author: lmf
     * @date: 2020/8/17 14:05
     * 导入促销活动并保存到数据库中,推送价格设置标签使用不一样的计算公式
     */
    @PostMapping("/importActiveTag")
    @ApiOperation(value = "导入参与促销活动的酒店并保存到数据库中",notes = "必须经过oauth授权")
    public Result<Object> importActiveTag(@RequestParam("file") MultipartFile file){
        return switchHotelActiveTagService.importActiveTag(file);
    }
    /**
     * @author: lmf
     * @date: 2020/9/3 11:34
     * 参与促销活动的酒店id重新推送价格
     */
    @PostMapping("/pushActiveTagPrice")
    @ApiOperation(value = "参与促销活动的酒店id重新推送价格",notes = "必须经过oauth授权")
    public Result<Object> pushActiveTagPrice(){
        return switchHotelActiveTagService.pushActiveTagPrice();
    }

    /**
     * @author: lmf
     * @date: 2020/9/8 14:05
     * 多线程推送房态房量推送数据
     * 比如:修改了价格公式或者比例，重新推送一个月的价格
     */
    @GetMapping("/pushDataByThead")
    @ApiOperation(value = "多线程推送房态房量推送数据",notes = "必须经过oauth授权")
    public void pushDataByThead(){
        switchPushRoomService.pushDataByThead();
    }
    /**
     * @author: lmf
     * @date: 2020/9/14 13:44
     * 重新推送最新的取消规则
     */
    @GetMapping("/setCancelRule")
    @ApiOperation(value = "重新推送取消规则",notes = "必须经过oauth授权")
    public void setCancelRule(){
        switchCreateRoomService.setCancelRule();
    }


    /****
    * @Author: lmf
    * @Date: 2020/9/24
     * 修改售卖房型取消规则最晚时间点
    */
    @PostMapping("/modifyCancelRule")
    @ApiOperation(value = "修改售卖房型取消规则最晚时间点",notes = "必须经过oauth授权")
    public Result<Object> modifyCancelRule(@RequestBody GetRoomListVo getRoomListVo){
        return switchCancelRuleSetService.setCancmodifyCancelRuleelRule(getRoomListVo);
    }

    /**
     * @author: lmf
     * @date: 2020/9/14 16:41
     * 为所有售卖房型推送一个月的价格,因为配置改变
     */
    @GetMapping("/pushRoomPriceByNewRate")
    @ApiOperation(value = "重新推送价格",notes = "必须经过oauth授权")
    public void pushRoomPriceByNewRate(){
        switchPushRoomService.pushRoomPriceByNewRate();
    }

    /**
     * @author: lmf
     * @date: 2020/9/15 11:27
     * 获取售卖房型列表
     */
    @PostMapping("/getRoomList")
    @ApiOperation(value = "获取售卖房型列表",notes = "必须经过oauth授权")
    public Result<Object> getRoomList(@RequestBody GetRoomListVo getRoomListVo){
        return switchCreateRoomService.getRoomList(getRoomListVo);
    }

    /**
     * @author: lmf
     * @date: 2020/9/18 14:03
     * 设置售卖房型无效
     */
    @GetMapping("/loseRoom")
    @ApiOperation(value = "获取售卖房型列表",notes = "必须经过oauth授权")
    public Result<Object> getRoomList(){
        return switchCreateRoomService.loseRoom();
    }

    /***
     * @Author: lmf
     * @Date: 2020/9/21
     * 上传参与取消规则的酒店id
     */
    @PostMapping("/upCancel")
    @ApiOperation(value = "上传参与取消规则的酒店id",notes = "必须经过oauth授权")
    public Result<Object> upCancel(@RequestParam("excelFile") MultipartFile excelFile) {
        if(excelFile.isEmpty()){
            return new Result<>("上传失败");
        }
        return switchCancelRuleSetService.upCancel(excelFile);
    }
    /***
    * @Author: lmf
    * @Date: 2020/9/22
     * 为指定售卖房型重新推送一个月的价格数据
    */
    @PostMapping("/pushBySpecial")
    @ApiOperation(value = "为指定售卖房型重新推送一个月的价格数据",notes = "必须经过oauth授权")
    public Result<Object> pushBySpecial(){
        switchPushRoomService.pushBySpecial();
        return new Result<>();
    }

    /**
     * @author: lmf
     * @time: 2020/10/19 18:15
     * 更新售卖房型餐食信息
     */
    @PostMapping("/updateCreateRoomBreak")
    @ApiOperation(value="updateCreateRoomBreak",notes = "必须经过oauth授权")
    public Result<Object> updateCreateRoomCancle(PushHotelBreakfastVo pushHotelBreakfastVo){
        return switchCreateRoomService.updateCreateRoomBreak(pushHotelBreakfastVo);
    }

    /**
     * @author: lmf
     * @time: 2020/10/28 20:33
     * 跑失效的售卖房型再次效验餐食信息是否符合
     */
    @PostMapping("/updateCreateRoomBreakAgein")
    @ApiOperation(value="updateCreateRoomBreak",notes = "必须经过oauth授权")
    public Result<Object> updateCreateRoomBreakAgein(){
        return switchCreateRoomService.updateCreateRoomBreakAgein();
    }


    /**
     * @author: lmf
     * @time: 2020/10/19 18:15
     * 美团产品失效，携程产品也做相关失效
     */
    @PostMapping("/productFailure")
    @ApiOperation(value="productFailure",notes = "必须经过oauth授权")
    public Result<Object> productFailure(@RequestBody ProductFailureVo productFailureVo){
        return switchCreateRoomService.productFailure(productFailureVo);
    }
    /**
     * @author: lmf
     * @time: 2020/10/19 18:15
     * 美团新增产品
     */
    @PostMapping("/productNewAdd")
    @ApiOperation(value="productNewAdd",notes = "必须经过oauth授权")
    public Result<Object> productNewAdd(@RequestBody ProductNewAddVo productNewAddVo){
        return switchCreateRoomService.productNewAdd(productNewAddVo);
    }

    /**
     *
     * @author: lmf
     * @time: 2020/10/29 16:25
     * 设置库存为1
     */
    @PostMapping("/initRoomNum")
    @ApiOperation(value="initRoomNum",notes = "必须经过oauth授权")
    public Result<Object> initRoomNum(){
        return switchPushRoomService.initRoomNum();
    }


    /**
     * 美团房型失效接口
     */
    @PostMapping("/roomFailure")
    @ApiOperation(value="roomFailure",notes = "必须经过oauth授权")
    public Result<Object> roomFailure(@RequestBody MtHotelRoomDownVo mtHotelRoomDownVo){

        return switchCreateRoomService.roomFailure(mtHotelRoomDownVo);
    }

    /**
     * 清除缓存
     */
    @PostMapping("/removesCache")
    @ApiOperation(value="removesCache",notes = "必须经过oauth授权")
    public Result<Object> removesCache(){
        List<SwitchCreateRoomFailureEntity> switchCreateRoomFailureEntities=switchCreateRoomFailureMapper.selectAll();
        for(SwitchCreateRoomFailureEntity switchCreateRoomFailureEntity:switchCreateRoomFailureEntities){
            String key3=CommonConstants.SWITCH_SELLING_REDIS_BY_MT+switchCreateRoomFailureEntity.getMtHotelId()+"_"+switchCreateRoomFailureEntity.getMtGoodId();
            if(redisService.exists(key3)){
                redisService.remove(key3);
            }
        }
        return new Result<>();
    }

    /***
    * @Author: lmf
    * @Date: 2020/12/15
     * 设置取消规则
    */
    @PostMapping("/updateRoomCancelRule")
    @ApiOperation(value="updateRoomCancelRule",notes = "必须经过oauth授权")
    public Result<Object> updateRoomCancelRule(){
       List<SwitchCreateRoomEntity> switchCreateRoomEntities=switchCreateRoomMapper.selectAll();
       for(SwitchCreateRoomEntity switchCreateRoomEntity:switchCreateRoomEntities){
           String key=CommonConstants.SWITCH_CREATE_ROOM_CANCEL_RULE+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtGoodId()+"_1";
           if(redisService.exists(key)){
               continue;
           }
           key=CommonConstants.SWITCH_CREATE_ROOM_CANCEL_RULE+switchCreateRoomEntity.getMtHotelId()+"_"+switchCreateRoomEntity.getMtGoodId()+"_0";
           if(redisService.exists(key)){
               continue;
           }
           redisService.set(key,"0");
       }
       return new Result<>();
    }














}
